  package com.llw.bledemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.llw.bledemo.callback.BleCallback;
import com.llw.bledemo.utils.BleConstant;
import com.llw.bledemo.utils.BleHelper;
import com.llw.bledemo.utils.ByteUtils;
import com.llw.bledemo.utils.LineChartUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 数据交互
 *
 * @author llw
 */
public class DataExchangeActivity extends AppCompatActivity {

    private static final String TAG = DataExchangeActivity.class.getSimpleName();

    /**
     * Gatt
     */
    private BluetoothGatt bluetoothGatt;
    /**
     * 设备是否连接
     */
    private boolean isConnected = false;
    private boolean isRun = false;
    private int iTime = 0;
    private boolean isAlowPause;

    private LineChartUtils lineChartUtils;
//    private Entry entry=new Entry();

    /**
     * Gatt回调
     */
    private BleCallback bleCallback;
    private TextView jSinal;
    private TextView ySinal;
    private TextView jStance;
    private TextView yStance;
    private TextView jTime;
    private TextView yTime;
    private TextView resultText;
    private TextView text_data;

    private ArrayList list1 = new ArrayList<>(); //数据集合

    private ArrayList list2 = new ArrayList<>(); //数据集合

    private ArrayList list3 = new ArrayList<>(); //数据集合
    private ArrayList list4 = new ArrayList<>(); //数据集合
    private ArrayList list5 = new ArrayList<>(); //数据集合
    private ArrayList list6 = new ArrayList<>(); //数据集合
    private ArrayList list7 = new ArrayList<>(); //数据集合


    private ArrayList listDataA = new ArrayList<>(); //数据集合
    private ArrayList listDataB = new ArrayList<>(); //数据集合
    private ArrayList dataList = new ArrayList<>(); //数据集合

    //    文件输出流
    private FileOutputStream fileOutputStream;

    private LineChart mChart1;
    private LineChart mChart2;
    private LineChart mChart3;
    private LineChart mChart4;
    private Button stopButton;
    private Button fileButton;

    private final int ACTIVY_REFRESH = 0011;
    private SimpleDateFormat formatter;
    private Date curDate;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private static String fileName = "demo.txt";
    //    private static String filePath= Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
    private static String filePath = "/sdcard/test/";
    private static Object obj = new Object();
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ACTIVY_REFRESH:
                    mChart1.invalidate();
                    mChart2.invalidate();
                    mChart3.invalidate();
                    mChart4.invalidate();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_exchange);
        initUI();
        initData(DataExchangeActivity.this);

    }

    private void initData(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            formatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); //设置时间格式
        }
        isAlowPause = true;
        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isAlowPause) {
                    stopButton.setText("继续");
                    isAlowPause = false;
                } else {
                    isAlowPause = true;
                    stopButton.setText("暂停");
                }
            }
        });
        fileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                fileButton.setText("导出中");
                curDate = new Date(System.currentTimeMillis());
                writeLogFile(formatter.format(curDate) + " =============== ");
                for (Object str : dataList) {
                    if (writeLogFile(str.toString())){
//                        fileButton.setText("导出成功");
                        showMsg("导出文件成功");
                    }else {
//                        fileButton.setText("导出失败");
                        showMsg("导出文件失败");
                    }
                }

            }
        });
        isRun = true;
        if (isRun && isAlowPause) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (!Thread.currentThread().isInterrupted()) {
                        Message message = new Message();
                        message.what = ACTIVY_REFRESH;
                        //发送消息
                        DataExchangeActivity.this.handler.sendMessage(message);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }

                    }
                }
            }).start();
        }
        doResultLine();
    }

    public static void createFile() {
        File file = new File(filePath);
        if (!file.exists()) {
            boolean a = file.mkdir();
            Log.d("12345", String.valueOf(a));
        } else {
        }
    }

    public static boolean writeLogFile(String msg) {
        synchronized (obj) {
            try {
                createFile();
                File file = new File(filePath + fileName);
                Log.d("12345", filePath + fileName);
                FileWriter fw = null;
                if (file.exists()) {
                    if (file.length() > 10000)
                        fw = new FileWriter(file, false);
                    else
                        fw = new FileWriter(file, true);
                } else {
                    fw = new FileWriter(file, false);
                }

//                Date d = new Date();
//                SimpleDateFormat s = new SimpleDateFormat("MM-dd HH:mm:ss");
//                String dateStr = s.format(d);

//                fw.write(String.format("[%s] %s", dateStr, msg));
                fw.write(String.format("%s", msg));
                fw.write(13);
                fw.write(10);
                fw.flush();
                fw.close();
                return true;
            } catch (Throwable ex) {
                Log.e("LogFileUtils", "writeLogFile 2 异常 " + ex);
                ex.printStackTrace();
                return false;
            }
        }
    }

    private void initUI() {
        //初始化
        bleCallback = new BleCallback(this);
        //获取上个页面传递过来的设备
        BluetoothDevice device = getIntent().getParcelableExtra("device");
        //连接gatt 设置Gatt回调
        bluetoothGatt = device.connectGatt(this, false, bleCallback);
        //UI
        jSinal = findViewById(R.id.JtagSignal);
        jStance = findViewById(R.id.Jdistance);
        jTime = findViewById(R.id.JoverTime);
        ySinal = findViewById(R.id.YtagSignal);
        yStance = findViewById(R.id.Ydistance);
        yTime = findViewById(R.id.YoverTime);
        resultText = findViewById(R.id.relust);
        mChart1 = findViewById(R.id.line_chat1);
        mChart2 = findViewById(R.id.line_chat2);
        mChart3 = findViewById(R.id.line_chat3);
        mChart4 = findViewById(R.id.line_chat4);
        text_data = findViewById(R.id.text_data);
        stopButton = findViewById(R.id.stopButton);
        fileButton = findViewById(R.id.fileStart);


    }

    private void doResultLine() {
        Description description = new Description();
        description.setText("结果");
        mChart4.setDescription(description);
        //是否绘制网格背景
        mChart4.setDrawGridBackground(true);
        //x轴的设置
        XAxis xAxis = mChart4.getXAxis();
        //将x轴的描述（文字 or 数字）显示在x轴下方
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //是否绘制x轴的网格线
        xAxis.setDrawGridLines(true);
        //是否绘制x轴的轴线
        xAxis.setDrawAxisLine(true);
        //y轴设置
        YAxis yAxis = mChart4.getAxisLeft();
        yAxis.resetAxisMaximum();
        yAxis.resetAxisMinimum();
        yAxis.setAxisMaximum(6);
        yAxis.setAxisMinimum(0);
        YAxis rAxis = mChart4.getAxisRight();
        //隐藏右边Y轴
        rAxis.setEnabled(false);
        //y轴提供数据的区间个数5个  false:是否均匀显示数据
        yAxis.setLabelCount(6, false);

    }

    private void doSomething() {
        stopButton.setVisibility(View.VISIBLE);
        fileButton.setVisibility(View.VISIBLE);
        lineChartUtils = new LineChartUtils("近点标签信号", "远点标签信号", list1, list4, mChart1);
        lineChartUtils = new LineChartUtils( "近点距离", "远点距离",list2, list5, mChart2);
        lineChartUtils = new LineChartUtils( "近点超时时间","远点超时时间", list3, list6, mChart3);
        mChart4.setData(getLineData());
    }

    private LineData   getLineData() {
        LineDataSet dataSet = new LineDataSet(list7, "结果");
        dataSet.setLineWidth(2.5f);
        //圆圈的大小
        dataSet.setCircleHoleRadius(4.5f);
        //设置颜色
        dataSet.setHighLightColor(Color.rgb(244, 0, 0));
        //是否显示圆点处的数据
        dataSet.setDrawValues(true);

        LineData lineData = new LineData(dataSet);
        return lineData;

    }

    /**
     * 断开设备连接
     */
    private void disconnectDevice() {
        if (isConnected && bluetoothGatt != null) {
            bluetoothGatt.disconnect();
        }
    }

    /**
     * Toast提示
     *
     * @param msg 内容
     */
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isRun = false;
    }

    public void setContent(byte[] ss) {
        String content1=ByteUtils.bytesToHexString(ss);
        String content2= Arrays.toString(ss);
//        Log.d("BleCallback", content1+"   "+content2);
        String content=content2.split("]")[0].split("\\[")[1];
        String[] strs=content.split(",");
        String othersString=subStringToComma(content1,2);
        String[] strs2=othersString.split(",");
//        for (String str : strs) {
//            Log.d("BleCallback", str);
//        }
        String[] hello=new String[7];
        hello[0]=strs[0];
        hello[1]=String.valueOf(Integer.parseInt(strs2[1],16));
        hello[2]=String.valueOf(Integer.parseInt(strs2[2],16));
        hello[3]=strs[3];
        hello[4]=String.valueOf(Integer.parseInt(strs2[4],16));
        hello[5]=String.valueOf(Integer.parseInt(strs2[5],16));
        hello[6]=String.valueOf(Integer.parseInt(strs2[6],16));
        if (isAlowPause) {
            dataList.add(Arrays.toString(hello));
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isAlowPause) {
                    iTime++;
                    jSinal.setText(hello[0]);
                    jStance.setText(hello[1]);
                    jTime.setText(hello[2]);
                    ySinal.setText(hello[3]);
                    yStance.setText(hello[4]);
                    yTime.setText(hello[5]);
                    resultText.setText(hello[6]);
                    list1.add(new Entry(iTime,Float.parseFloat(hello[0])));
                    list2.add(new Entry(iTime,Float.parseFloat(hello[1])));
                    list3.add(new Entry(iTime,Float.parseFloat(hello[2])));
                    list4.add(new Entry(iTime,Float.parseFloat(hello[3])));
                    list5.add(new Entry(iTime,Float.parseFloat(hello[4])));
                    list6.add(new Entry(iTime,Float.parseFloat(hello[5])));
                    list7.add(new Entry(iTime,Float.parseFloat(hello[6])));
                    curDate = new Date(System.currentTimeMillis());
                    text_data.setText(formatter.format(curDate) + "  :  " + Arrays.toString(hello) +"   长度:"+  iTime);
                    doSomething();
                } else {
                    showMsg("暂停中");
                }
            }
        });

    }

    public static String subStringToComma(String str, Integer regex) {
        char[] chars = str.toCharArray();
        String temp = "";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i <= chars.length - 1; i++) {
            temp += chars[i];
            if (i == chars.length - 1) {
                result.append(temp);
                break;
            }
            if (temp.length() >= regex) {
                temp += ",";
                result.append(temp);
                temp = "";
            }
        }
        return result.toString();

    }
}